package site.luojie.netty.rpc.consumer.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import site.luojie.netty.rpc.common.base.NettyRpcRequest;
import site.luojie.netty.rpc.common.base.NettyRpcResult;

import java.util.concurrent.Callable;

/**
 * @author jie.luo
 * @since 2020-07-06 23:57
 **/
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private NettyRpcRequest sendMessage;
    private Object result;

    /**
     * 连接成功是自动执行
     *
     * @param ctx ChannelHandlerContext
     * @throws Exception e
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.context = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof NettyRpcResult) {
            NettyRpcResult nettyRpcResult = (NettyRpcResult) msg;
            result = nettyRpcResult.getResult();
        }

        // 获取服务端回执数据后，唤醒等待线程
        notify();
    }

    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(sendMessage);
        // 发送参数后，等待服务端回执唤醒
        wait();
        return result;
    }

    public NettyRpcRequest getSendMessage() {
        return sendMessage;
    }

    public void setSendMessage(NettyRpcRequest sendMessage) {
        this.sendMessage = sendMessage;
    }
}
